<template>
  <div class="step-content">
    <h3>实名认证</h3>
    <p class="tip">认证后可使用更多功能（可选）</p>

    <el-form
        ref="authFormRef"
        :model="formData"
        label-width="100px"
        class="auth-form"
        :disabled="isVerified"
    >
      <el-form-item label="真实姓名">
        <el-input
            v-model="formData.realName"
            placeholder="请输入真实姓名"
            clearable
            @blur="() => { validateRealName(); updateParent(); }"
        />
        <div v-if="realNameError" class="error-tip">{{ realNameError }}</div>
      </el-form-item>

      <el-form-item label="身份证号">
        <el-input
            v-model="formData.idCard"
            placeholder="请输入身份证号码"
            maxlength="18"
            clearable
            @blur="() => { validateIdCard(); updateParent(); }"
        />
        <div v-if="idCardError" class="error-tip">{{ idCardError }}</div>
      </el-form-item>

      <el-form-item label="身份证照片">
        <div class="id-card-upload-container">
          <!-- 身份证正面 -->
          <div class="id-card-side">
            <div class="side-title">身份证正面上传</div>
            <div class="upload-area" :class="{
              'has-image': formData.idCardUrl.front,
              'completed': isVerified
            }">
              <div v-if="formData.idCardUrl.front" class="preview-container">
                <img :src="getFullUrl(formData.idCardUrl.front)" class="preview-image" />
                <div class="image-overlay" v-if="!isVerified">
                  <span class="preview-action" @click="handlePictureCardPreview('front')">
                    <i class="el-icon-zoom-in"></i> 预览
                  </span>
                  <span class="delete-action" @click="handleRemove('front')">
                    <i class="el-icon-delete"></i> 删除
                  </span>
                </div>
                <div class="completed-badge" v-if="isVerified">
                  <i class="el-icon-success"></i>
                </div>
              </div>
              <div v-else class="upload-prompt">
                <div class="id-card-example front-example">
                  <div class="example-text">中华人民共和国</div>
                  <div class="example-text">居民身份证</div>
                </div>
                <el-upload
                    :action="uploadAction"
                    :headers="uploadHeaders"
                    :show-file-list="false"
                    :on-success="(res, file) => handleUploadSuccess(res, file, 'front')"
                    :before-upload="beforeUpload"
                    name="files"
                    accept="image/jpeg,image/png"
                    :disabled="isVerified"
                >
                  <el-button type="primary" icon="el-icon-upload" :disabled="isVerified">上传正面</el-button>
                </el-upload>
                <p class="upload-tip">请上传身份证头像面</p>
              </div>
            </div>
          </div>

          <!-- 身份证背面 -->
          <div class="id-card-side">
            <div class="side-title">身份证反面上传</div>
            <div class="upload-area" :class="{
              'has-image': formData.idCardUrl.back,
              'completed': isVerified
            }">
              <div v-if="formData.idCardUrl.back" class="preview-container">
                <img :src="getFullUrl(formData.idCardUrl.back)" class="preview-image" />
                <div class="image-overlay" v-if="!isVerified">
                  <span class="preview-action" @click="handlePictureCardPreview('back')">
                    <i class="el-icon-zoom-in"></i> 预览
                  </span>
                  <span class="delete-action" @click="handleRemove('back')">
                    <i class="el-icon-delete"></i> 删除
                  </span>
                </div>
                <div class="completed-badge" v-if="isVerified">
                  <i class="el-icon-success"></i>
                </div>
              </div>
              <div v-else class="upload-prompt">
                <div class="id-card-example back-example">
                  <div class="example-text">签发机关</div>
                  <div class="example-text">有效期限</div>
                </div>
                <el-upload
                    :action="uploadAction"
                    :headers="uploadHeaders"
                    :show-file-list="false"
                    :on-success="(res, file) => handleUploadSuccess(res, file, 'back')"
                    :before-upload="beforeUpload"
                    name="files"
                    accept="image/jpeg,image/png"
                    :disabled="isVerified"
                >
                  <el-button type="primary" icon="el-icon-upload" :disabled="isVerified">上传背面</el-button>
                </el-upload>
                <p class="upload-tip">请上传身份证国徽面</p>
              </div>
            </div>
          </div>
        </div>

        <p v-if="idCardImgError" class="error-tip">请上传身份证正面和背面照片</p>
        <el-dialog v-model="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
        <div class="submit-button-container">
          <el-button
              type="primary"
              @click="handleSubmit"
              :loading="submitting"
              :disabled="isVerified || isFormEmpty"
              :class="{ 'success-button': isVerified }"
          >
            <span v-if="isVerified">
              <i class="el-icon-success"></i> 已提交
            </span>
            <span v-else>提交信息</span>
          </el-button>
          <p v-if="submitError" class="error-tip">{{ submitError }}</p>
        </div>
      </el-form-item>
    </el-form>

    <div class="identity-confirmation">
      <el-alert
          :title="`您选择的身份：${identityText}`"
          type="warning"
          :closable="false"
          show-icon
      >
        <template #default>
          <p>身份确认后不可更改，请仔细核对</p>
        </template>
      </el-alert>
    </div>

    <div class="step-buttons">
      <el-button @click="$emit('prev')">上一步</el-button>
      <el-button
          type="primary"
          @click="handleNextStep"
      >
        下一步
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits,watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 定义 BASE_URL
const BASE_URL = window.BASE_URL || 'http://localhost:8080';

// 表单引用
const authFormRef = ref(null)
const dialogVisible = ref(false)
const dialogImageUrl = ref('')
const submitting = ref(false)
const idCardError = ref('')
const realNameError = ref('')
const idCardImgError = ref(false)
const submitError = ref('')

const props = defineProps({
  identityText: String,
  authForm: Object,
  selectedIdentity: {
    type: Number,
    default: 0
  },
  isVerified: Boolean // 接收父组件的认证状态
})
// 在 setup 部分添加
watch(() => props.isVerified, (newVal) => {
  console.log('[子组件] 接收到父组件的认证状态:', newVal)
}, { immediate: true })

import { onMounted, onUnmounted } from 'vue'

onMounted(() => {
  console.log('[子组件] StepVerification 已挂载')
})

onUnmounted(() => {
  console.log('[子组件] StepVerification 已卸载')
})

const emit = defineEmits(['prev', 'next', 'update:authForm', 'submit-success'])

// 使用本地 formData 替代 props.authForm
const formData = ref({
  realName: props.authForm?.realName || '',
  idCard: props.authForm?.idCard || '',
  idCardUrl: props.authForm?.idCardUrl || { front: '', back: '' }
})

// 监听父组件传入的 authForm 变化
watch(() => props.authForm, (newVal) => {
  formData.value = { ...newVal }
}, { deep: true, immediate: true })

// 计算上传URL
const uploadAction = computed(() => {
  return `${BASE_URL}/api/v1/upload?type=idcard`
})

const uploadHeaders = computed(() => {
  const token = localStorage.getItem('token')
  return {
    Authorization: token || ''
  }
})

// 获取完整URL（仅用于显示）
const getFullUrl = (path) => {
  return path ? `${BASE_URL}${path}` : ''
}

// 真实姓名验证
const validateRealName = () => {
  if (!formData.value.realName) {
    realNameError.value = '真实姓名不能为空'
    return false
  }
  realNameError.value = ''
  return true
}

// 身份证格式验证
const validateIdCard = () => {
  const idCard = formData.value.idCard
  if (!idCard) {
    idCardError.value = ''
    return true
  }

  // 简单验证身份证格式
  const reg = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/
  if (!reg.test(idCard)) {
    idCardError.value = '身份证格式不正确'
    return false
  } else {
    idCardError.value = ''
    return true
  }
}

// 检查表单是否为空
const isFormEmpty = computed(() => {
  return !formData.value.realName &&
      !formData.value.idCard &&
      !formData.value.idCardUrl.front &&
      !formData.value.idCardUrl.back
})

// 更新父组件数据
const updateParent = () => {
  emit('update:authForm', formData.value);
}

// 图片预览
const handlePictureCardPreview = (side) => {
  dialogImageUrl.value = getFullUrl(formData.value.idCardUrl[side])
  dialogVisible.value = true
}

// 上传前检查
const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('上传图片大小不能超过 5MB!')
    return false
  }
  return true
}

// 处理上传成功
const handleUploadSuccess = (response, file, side) => {
  if (response && response.urls && response.urls.length > 0) {
    const relativePath = response.urls[0];

    // 更新对应面的URL（只存储相对路径）
    formData.value.idCardUrl[side] = relativePath;

    // 通知父组件更新
    updateParent();

    // 检查图片完整性
    idCardImgError.value = !formData.value.idCardUrl.front || !formData.value.idCardUrl.back;

    ElMessage.success('上传成功');
  }
}

// 处理移除
const handleRemove = async (side) => {
  try {
    if (!formData.value.idCardUrl[side]) return;

    const relativePath = formData.value.idCardUrl[side];

    await deleteImageOnServer(relativePath);

    // 清空对应的图片路径
    formData.value.idCardUrl[side] = '';
    updateParent();

    idCardImgError.value = !formData.value.idCardUrl.front || !formData.value.idCardUrl.back;

    ElMessage.success('删除成功');
  } catch (error) {
    ElMessage.error(`删除失败: ${error.message || '服务器错误'}`);
    console.error('删除失败:', error);
  }
}

// 后端API请求处理
const handleJsonResult = async (response) => {
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  const result = await response.json();

  if (result.code !== 2000) {
    throw new Error(result.message || '操作失败');
  }

  return result;
}

// 调用后端删除接口
const deleteImageOnServer = async (filePath) => {
  const token = localStorage.getItem('token') || '';

  const response = await fetch(`${BASE_URL}/api/v1/delete`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token
    },
    body: JSON.stringify([filePath])
  });

  await handleJsonResult(response);
}

// 检查身份证号是否已被使用
const checkIdCardUnique = async () => {
  try {
    const token = localStorage.getItem('token') || '';
    const response = await fetch(`${BASE_URL}/api/v1/users/checkIdCard?idCard=${formData.value.idCard}`, {
      method: 'GET',
      headers: {
        'Authorization': token
      }
    });

    const result = await handleJsonResult(response);

    // 假设接口返回数据格式: { exists: true } 表示身份证已被使用
    if (result.data && result.data.exists) {
      throw new Error('该身份证号已被绑定，请使用其他身份证');
    }

    return true;
  } catch (error) {
    throw error;
  }
}

// 处理提交认证
const handleSubmit = async () => {
  submitting.value = true;
  submitError.value = '';
  idCardImgError.value = false;
  realNameError.value = '';
  idCardError.value = '';

  try {
    // 验证必填项
    const isRealNameValid = validateRealName();
    const isIdCardValid = validateIdCard();

    if (!isRealNameValid || !isIdCardValid) {
      throw new Error('请完善表单信息');
    }

    // 检查图片数量
    if (!formData.value.idCardUrl.front || !formData.value.idCardUrl.back) {
      idCardImgError.value = true;
      throw new Error('请上传身份证正面和背面照片');
    }

    // 检查身份证号是否已被使用
    await checkIdCardUnique();

    // 确保更新父组件数据
    updateParent();

    // 触发提交成功事件（父组件会设置 isVerified）
    emit('submit-success', {
      realName: formData.value.realName,
      idCard: formData.value.idCard,
      idCardUrl: formData.value.idCardUrl
    });

    ElMessage.success('实名认证成功');

  } catch (e) {
    submitError.value = e.message;
    ElMessage.error(e.message);
  } finally {
    submitting.value = false;
  }
}

// 处理下一步按钮
const handleNextStep = async () => {
  // 使用父组件传递的状态
  if (props.isVerified) {
    emit('next');
    return;
  }

  // 如果表单有部分填写但未提交
  const hasPartialInfo =
      formData.value.realName ||
      formData.value.idCard ||
      formData.value.idCardUrl.front ||
      formData.value.idCardUrl.back;

  if (hasPartialInfo) {
    try {
      await ElMessageBox.confirm(
          '您还未完成实名认证，确定跳过吗？跳过将清空已填写的信息。',
          '提示',
          {
            confirmButtonText: '确定跳过',
            cancelButtonText: '继续认证',
            type: 'warning'
          }
      );

      // 清空表单
      formData.value = {
        realName: '',
        idCard: '',
        idCardUrl: { front: '', back: '' }
      };
      idCardImgError.value = false;
      realNameError.value = '';
      idCardError.value = '';

      // 通知父组件更新
      updateParent();

      // 进入下一步
      emit('next');

    } catch {
      // 用户取消操作
    }
  } else {
    // 没有任何填写，直接下一步
    emit('next');
  }
}
</script>

<!-- 样式保持不变 -->
<style scoped>
.id-card-reader {
  margin-bottom: 20px;
  text-align: center;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}

.reader-tip {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
}

.error-tip {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
}

.step-content {
  position: relative;
}

.step-buttons {
  margin-top: 30px;
  text-align: center;
  display: flex;
  justify-content: center;
  gap: 20px;
}

/* 身份证上传容器样式 */
.id-card-upload-container {
  display: flex;
  gap: 30px;
  margin-top: 15px;
}

.id-card-side {
  flex: 1;
  text-align: center;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  background: #fafafa;
}

.side-title {
  font-weight: bold;
  margin-bottom: 15px;
  font-size: 16px;
  color: #333;
}

.upload-area {
  min-height: 220px;
  height: 220px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  background-color: #fff;
  transition: border-color 0.3s;
  position: relative;
  overflow: hidden;
}

.upload-area.has-image {
  border: 1px solid #409eff;
}

.upload-area.completed {
  border: 2px solid #67c23a;
  background-color: #f0f9eb;
}

.upload-area:hover {
  border-color: #409eff;
}

.upload-prompt {
  padding: 20px;
  text-align: center;
}

.id-card-example {
  width: 200px;
  height: 120px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin: 0 auto 15px;
  background: #f0f2f5;
}

.front-example {
  background: linear-gradient(135deg, #f5f7fa 25%, #e4e7ed 100%);
}

.back-example {
  background: linear-gradient(135deg, #e4e7ed 25%, #f5f7fa 100%);
}

.example-text {
  font-size: 14px;
  color: #606266;
  margin: 5px 0;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 10px;
}

.preview-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.image-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  padding: 8px;
  display: flex;
  justify-content: center;
  gap: 15px;
}

.completed-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  background: #67c23a;
  color: white;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  z-index: 10;
}

.preview-action, .delete-action {
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  font-size: 12px;
}

.preview-action:hover, .delete-action:hover {
  color: #409eff;
}

.preview-action i, .delete-action i {
  margin-right: 4px;
}

.identity-confirmation {
  margin-top: 25px;
}

.submit-button-container {
  text-align: center;
  margin-top: 20px;
}

.success-button {
  background-color: #67c23a !important;
  border-color: #67c23a !important;
}

.success-button:hover {
  background-color: #5daf34 !important;
  border-color: #5daf34 !important;
}

.success-button i {
  margin-right: 5px;
}
</style>
